/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.elcom.dailyexpress;

import com.elcom.dailyexpress.mongodbdao.BscDao;
import com.elcom.dailyexpress.mongodbdao.CellDao;
import com.elcom.dailyexpress.mongodbdao.MongoDbAccess;
import com.elcom.dailyexpress.requestprocess2.GetMessageStatusProcessor;
import com.elcom.dailyexpress.requestprocess2.SendMessageRequestProcessor;
import com.elcom.emocbc.cbcresponseparser.ResponseParser;
import com.elcom.emocbc.cbcresponseparser.cbcresponse.CbcMessageResponse;
import com.elcom.emocbc.cbcresponseparser.cbcresponse.CbcRequestType;
import com.elcom.emocbc.cbcresponseparser.cbcresponse.GetBscCellsResponse;
import com.elcom.emocbc.cbcresponseparser.cbcresponse.GetBscsResponse;
import com.elcom.emocbc.cbcresponseparser.cbcresponse.structure.BscInfo;
import com.elcom.emocbc.cbcresponseparser.cbcresponse.structure.BscProperty;
import com.elcom.emocbc.cbcresponseparser.cbcresponse.structure.BscStatus;
import com.elcom.emocbc.cbcresponseparser.cbcresponse.structure.CellInfo;
import com.elcom.emocbc.cbcresponseparser.cbcresponse.structure.ReturnValue;
import com.elcom.emocbc.mongodb.Bsc;
import com.elcom.emocbc.mongodb.Cell;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author GiangLT
 */
public class smscb extends HttpServlet {

    private ResponseParser<CbcMessageResponse> parser = new ResponseParser<CbcMessageResponse>();
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String smscbCenterId = request.getParameter("smscbCenterId");
        logger.info("<<< [SMSCB {}]Received a request {}", smscbCenterId, request.getRequestURI());
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */

            String functionName = request.getParameter("fn");
            if (functionName.equals(CbcRequestType.GET_BSCS)) {
                BscDao bscDao = new BscDao(MongoDbAccess.getInstance().getDatastore());
                try {
                    Multimap<String, String> smscbBscMap = constructSmscbBscMap();

                    List<Bsc> bscs = bscDao.findBscsFromList(smscbBscMap.get(smscbCenterId));
                    logger.info("[SMSCB {}]Found {} BSCs", smscbCenterId, bscs.size());
                    List<BscInfo> bscInfos = new ArrayList<BscInfo>();
                    for (Bsc bsc : bscs) {
                        BscInfo bscInfo = new BscInfo();
                        List<BscProperty> bscProperties = new ArrayList<BscProperty>();
                        bscProperties.add(new BscProperty("name", bsc.getBscName()));
                        bscProperties.add(new BscProperty("bscid", bsc.getBscId()));
                        bscProperties.add(new BscProperty("version", bsc.getVersion() == null ? "" : bsc.getVersion().toString()));
                        bscProperties.add(new BscProperty("primaryport", ""));
                        bscProperties.add(new BscProperty("vendor", bsc.getVendor()));
                        bscProperties.add(new BscProperty("protocol", bsc.getProtocol()));
                        bscProperties.add(new BscProperty("bscprimaryaddress", bsc.getPrimaryAddress()));
                        bscInfo.setProperties(bscProperties);

                        BscStatus bscStatus = new BscStatus();
                        bscStatus.setDescription(bsc.getDescription());
                        bscStatus.setStatus(bsc.getStatus());
                        bscStatus.setReconnectionNumber(0);
                        bscStatus.setInitializationTime("10");
                        bscInfo.setStatus(bscStatus);
                        bscInfos.add(bscInfo);
                    }

                    GetBscsResponse getBscsResponse = new GetBscsResponse();
                    getBscsResponse.setBscInfos(bscInfos);
                    getBscsResponse.setStatus("SUCCESS");
                    out.println(parser.marshall(getBscsResponse));
                } catch (Exception ex) {
                    logger.error("", ex);
                }
            } else if (functionName.equals(CbcRequestType.GET_BSC_CELLS)) {
                String bscid = request.getParameter("bscid");
                CellDao cellDao = new CellDao(MongoDbAccess.getInstance().getDatastore());
                List<Cell> cells;
                try {
                    cells = cellDao.findByBscId(bscid);
                    logger.info("[SMSCB {}]Found {} Cells for BSC {}", smscbCenterId, cells.size(), bscid);
                    List<CellInfo> cellInfos = new ArrayList<CellInfo>(cells.size());
                    for (Cell cell : cells) {
                        CellInfo cellInfo = new CellInfo();
                        cellInfo.setBscId(bscid);
                        cellInfo.setCi(cell.getCellId().toString());
                        cellInfo.setGatewayId(cell.getGatewayId());
                        cellInfo.setId(cell.getCellKey().toString());
                        cellInfo.setLac(cell.getLac());
                        cellInfo.setMcc(cell.getMcc());
                        cellInfo.setMnc(cell.getMnc());
                        cellInfo.setName(cell.getCellName());
                        cellInfo.setStatus(cell.getStatus());
                        cellInfo.setStatusDescription(cell.getStatusDecription());
                        cellInfos.add(cellInfo);
                    }

                    ReturnValue cellReturnValue = new ReturnValue("list", cellInfos);

                    GetBscCellsResponse bscCellsResponse = new GetBscCellsResponse();
                    bscCellsResponse.setCellReturnValue(cellReturnValue);
                    bscCellsResponse.setRequest(CbcRequestType.GET_BSC_CELLS);
                    bscCellsResponse.setStatus("SUCCESS");
                    out.println(parser.marshall(bscCellsResponse));
                } catch (Exception ex) {
                    logger.error("", ex);
                }

            } else if (functionName.equals(CbcRequestType.SEND_MESSAGE)) {
                SendMessageRequestProcessor sendMessageRequestProcessor = new SendMessageRequestProcessor(request, response);
                try {
                    sendMessageRequestProcessor.process();
                } catch (Exception ex) {
                    logger.error("", ex);
                }
            } else if (functionName.equals(CbcRequestType.GET_MESSAGE_STATUS)) {
                GetMessageStatusProcessor getMessageStatusProcessor = new GetMessageStatusProcessor(request, response);
                try {
                    getMessageStatusProcessor.process();
                } catch (Exception ex) {
                    logger.error("", ex);
                }
            }

//            Set<Entry<String, String[]>> paramMap = request.getParameterMap().entrySet();
//            out.println();
//            for (Entry<String, String[]> entry : paramMap) {
//                String key = entry.getKey();
//                out.print(key + ": ");
//                String[] values = entry.getValue();
//                StringBuilder valueStr = new StringBuilder();
//                for (String value : values) {
//                    valueStr.append(value);
//                    valueStr.append(" ");
//                }
//                out.println(valueStr);
//            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private Multimap<String, String> constructSmscbBscMap() {
        Multimap<String, String> smscbBscMap = ArrayListMultimap.create();
        smscbBscMap.put("1", "10043");
        smscbBscMap.put("1", "10001");
        smscbBscMap.put("1", "10002");
        smscbBscMap.put("1", "10021");
        smscbBscMap.put("1", "10031");
        smscbBscMap.put("1", "10004");
        smscbBscMap.put("1", "19");
        smscbBscMap.put("1", "10037");
        smscbBscMap.put("1", "10022");
        smscbBscMap.put("2", "10008");
        smscbBscMap.put("2", "10007");
        smscbBscMap.put("2", "10006");
        smscbBscMap.put("2", "10005");
        smscbBscMap.put("2", "10038");
        smscbBscMap.put("2", "20");
        smscbBscMap.put("2", "10024");
        smscbBscMap.put("2", "10032");
        smscbBscMap.put("2", "10023");
        smscbBscMap.put("2", "14");
        smscbBscMap.put("3", "10010");
        smscbBscMap.put("3", "10009");
        smscbBscMap.put("3", "10025");
        smscbBscMap.put("3", "10026");
        smscbBscMap.put("3", "10011");
        smscbBscMap.put("3", "10039");
        smscbBscMap.put("3", "16");
        smscbBscMap.put("3", "10012");
        smscbBscMap.put("3", "10034");
        smscbBscMap.put("4", "10028");
        smscbBscMap.put("4", "10027");
        smscbBscMap.put("4", "10016");
        smscbBscMap.put("4", "10015");
        smscbBscMap.put("4", "10014");
        smscbBscMap.put("4", "10013");
        smscbBscMap.put("4", "10040");
        smscbBscMap.put("4", "10035");
        smscbBscMap.put("4", "17");
        smscbBscMap.put("5", "18");
        smscbBscMap.put("5", "10042");
        smscbBscMap.put("5", "10036");
        smscbBscMap.put("5", "10030");
        smscbBscMap.put("5", "10029");
        smscbBscMap.put("5", "10020");
        smscbBscMap.put("5", "10019");
        smscbBscMap.put("5", "10018");
        smscbBscMap.put("5", "10017");
        return smscbBscMap;
    }
}
